interface SEOConfig {
  title?: string;
  description?: string;
  keywords?: string;
  image?: string;
  url?: string;
  type?: string;
}

export const useSEO = (config: SEOConfig = {}) => {
  const route = useRoute();
  const runtimeConfig = useRuntimeConfig();

  const defaultTitle = '电商助手 - AI智能SKU生成器 | 商品标题优化工具';
  const defaultDescription =
    '电商助手是专业的AI电商运营工具，为拼多多、淘宝、京东商家提供SKU智能生成、商品标题优化服务。3秒生成防比价SKU，智能优化商品标题，提升转化率40%。';
  const siteUrl = runtimeConfig.public?.siteUrl || 'https://your-domain.com';

  const seoTitle = computed(() => {
    if (!config.title) return defaultTitle;
    return config.title.includes('电商助手') ? config.title : `${config.title} | 电商助手`;
  });

  const seoDescription = computed(() => config.description || defaultDescription);
  const seoKeywords = computed(() => config.keywords || 'SKU生成器,商品标题生成,AI电商工具,防比价,拼多多,淘宝,京东,电商运营');
  const seoImage = computed(() => config.image || '/og-image.jpg');
  const seoUrl = computed(() => {
    if (config.url) return config.url;
    const baseUrl = typeof siteUrl === 'string' ? siteUrl : 'https://your-domain.com';
    return `${baseUrl}${route.path}`;
  });

  // 动态设置页面SEO
  useHead({
    title: seoTitle,
    meta: [
      { name: 'description', content: seoDescription },
      { name: 'keywords', content: seoKeywords },

      // Open Graph
      { property: 'og:title', content: seoTitle },
      { property: 'og:description', content: seoDescription },
      { property: 'og:image', content: seoImage },
      { property: 'og:url', content: seoUrl },
      { property: 'og:type', content: config.type || 'website' },

      // Twitter Card
      { name: 'twitter:title', content: seoTitle },
      { name: 'twitter:description', content: seoDescription },
      { name: 'twitter:image', content: seoImage },
    ],
    link: [{ rel: 'canonical', href: seoUrl }],
  });

  // 结构化数据生成器
  const generateStructuredData = (type: string, data: any) => {
    useHead({
      script: [
        {
          type: 'application/ld+json',
          innerHTML: JSON.stringify({
            '@context': 'https://schema.org',
            '@type': type,
            ...data,
          }),
        },
      ],
    });
  };

  return {
    seoTitle,
    seoDescription,
    seoKeywords,
    seoImage,
    seoUrl,
    generateStructuredData,
  };
};
